package com.example.sfm.controller.admin;

import com.alibaba.excel.EasyExcel;
import com.example.sfm.constant.MessageConstants;
import com.example.sfm.handler.TemplateStyleHandler;
import com.example.sfm.pojo.dto.GradesDto;
import com.example.sfm.pojo.dto.GradesImportDto;
import com.example.sfm.pojo.dto.GradesQueryDto;
import com.example.sfm.result.Result;
import com.example.sfm.service.IGradesService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author sfm
 * @since 2025-03-07
 */
@Tag(name = "管理员成绩管理", description = "管理员对成绩的管理接口")
@RestController("adminGradesController")
@RequestMapping("/admin/grades")
@RequiredArgsConstructor
@Slf4j
public class GradesController {
    private final IGradesService gradesService;

    /**
     * 创建成绩记录
     */
    @Operation(summary = "创建成绩记录", description = "根据提供的成绩信息创建一个新的成绩记录")
    @PostMapping("/create")
    public Result<?> createGrade(@RequestBody @Validated @Parameter(description = "成绩信息") GradesDto dto) {
        log.info("创建成绩: {}", dto);
        gradesService.createGrade(dto);
        return Result.success(MessageConstants.ADD_OK);
    }

    /**
     * 分页查询成绩
     */
    @Operation(summary = "分页查询成绩", description = "根据查询条件分页查询成绩列表")
    @GetMapping("/list")
    public Result<?> listGrades(@Validated @ParameterObject GradesQueryDto dto) {
        log.info("查询成绩列表: {}", dto);
        return Result.success(gradesService.listGrades(dto), MessageConstants.SELECT_OK);
    }

    /**
     * 更新成绩记录
     */
    @Operation(summary = "更新成绩记录", description = "根据成绩ID更新成绩信息")
    @PutMapping("/update/{id}")
    public Result<?> updateGrade(@PathVariable @Parameter(description = "成绩ID",in = ParameterIn.PATH) Integer id, @RequestBody @Validated @Parameter(description = "更新内容") GradesDto dto) {
        log.info("更新成绩: ID={}, 内容={}", id, dto);
        gradesService.updateGrade(id, dto);
        return Result.success(MessageConstants.OPERATION_SUCCESSFUL);
    }

    /**
     * 批量删除成绩
     */
    @Operation(summary = "批量删除成绩", description = "根据提供的成绩ID列表批量删除成绩")
    @DeleteMapping("/delete")
    public Result<?> deleteGrades(@RequestParam @Parameter(description = "成绩ID列表",in = ParameterIn.QUERY) List<Integer> ids) {
        log.info("批量删除成绩: IDs={}", ids);
        gradesService.deleteGrades(ids);
        return Result.success(MessageConstants.OPERATION_SUCCESSFUL);
    }

    /**
     * Excel导入成绩
     */
    @Operation(summary = "Excel导入成绩", description = "导入Excel文件中的成绩数据")
    @PostMapping("/import")
    public Result<?> importExcel(@RequestParam("file") @NotNull @Parameter(description = "上传的Excel文件") MultipartFile file) {
        log.info("导入成绩文件: {}", file.getOriginalFilename());
        gradesService.importFromExcel(file);
        return Result.success(MessageConstants.OPERATION_SUCCESSFUL);
    }

    /**
     * Excel导出成绩
     */
    @Operation(summary = "Excel导出成绩", description = "导出成绩数据到Excel文件")
    @GetMapping("/export")
    public void exportExcel(HttpServletResponse response, @ParameterObject GradesQueryDto dto) {
        log.info("导出成绩数据: {}", dto);
        gradesService.exportExcel(response, dto);
    }

    @Operation(summary = "下载成绩导入模板", description = "下载成绩导入模板文件")
    @GetMapping("/template")
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        String fileName = "成绩导入模板.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition",
                "attachment; filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));

        // 生成带说明的模板
        List<GradesImportDto> exampleData = Collections.singletonList(
                GradesImportDto.builder().studentNumber("10")
                        .courseCode("100")
                        .score(new BigDecimal("85.5"))
                        .examDate(LocalDate.of(2024, 3, 15))
                        .remark("期中考试").build());

        EasyExcel.write(response.getOutputStream(), GradesImportDto.class)
                .registerWriteHandler(new TemplateStyleHandler()) // 自定义样式
                .sheet("成绩数据")
                .doWrite(exampleData);
    }
}